package info.itloser.pltv.adapter

import android.content.Context
import android.content.res.ColorStateList
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import info.itloser.pltv.R
import info.itloser.pltv.bean.ChannelItem

/**
 * 说明：
 * 作者： itloser.info
 * 日期： 2022/1/17 10:15
 * 备注： https://blog.csdn.net/speverriver/article/details/79206692
 */
class ChannelAdapter(private val channels: List<ChannelItem>, private val context: Context) :
    RecyclerView.Adapter<ChannelAdapter.ChannelHolder>() {

    lateinit var onClick: OnClick

    class ChannelHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvChannelNo: TextView = itemView.findViewById(R.id.tv_channel_no)
        val tvChannelName: TextView = itemView.findViewById(R.id.tv_channel_name)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChannelHolder {

        //加载布局
        val view = LayoutInflater.from(context).inflate(R.layout.item_channel, parent, false)

        //返回布局给ViewHolder
        return ChannelHolder(view)

    }

    override fun onBindViewHolder(holder: ChannelHolder, position: Int) {

        //拿到当前项
        val channel = channels[position]

        //给布局赋值
        holder.tvChannelNo.text = noToString(channel.channelNo)
        holder.tvChannelName.text = channel.channelName
        if (channel.isCheck) {
            holder.itemView.setBackgroundColor(0xFF03DAC5.toInt())
        }else{
            holder.itemView.setBackgroundColor(0xFFFFFFFF.toInt())
        }

        //点击事件
        holder.itemView.setOnClickListener {
            onClick.onItemClick(position)

            //标记当前项 选中
            checkOne(position)
        }


    }

    override fun getItemCount(): Int {
        return channels.size
    }

    /**
     * 给 不满3位的数字补位
     */
    private fun noToString(no: Int): String {
        if (no < 10) {
            return "00$no"
        }
        if (no < 100) {
            return "0$no"
        }
        return "$no"
    }

    private fun checkOne(position: Int) {

        for (i in channels.indices) {

            if (channels[i].isCheck && position != i) {
                channels[i].isCheck = false
                this.notifyItemChanged(i)
            }

        }

        channels[position].isCheck = true
        this.notifyItemChanged(position)

    }


    /**
     * 给外部的接口
     */
    interface OnClick {

        fun onItemClick(position: Int)

    }


}

